import sys
from datetime import datetime, timedelta
from PySide2.QtWidgets import (QApplication, QDialog, QListWidgetItem, QMessageBox, 
                            QWidget, QFrame, QSplitter, QGroupBox, QGridLayout,
                            QLineEdit, QDateEdit, QTimeEdit, QComboBox, QSpinBox, QPushButton,
                            QLabel, QVBoxLayout, QHBoxLayout)  # 导入布局类
from PySide2.QtCore import Qt, QDate, QTime, QDateTime, QSize
from PySide2.QtGui import QIcon
from Ui_schedule_manager import Ui_ScheduleManagerDialog  # 导入生成的UI类

class ScheduleItem(QWidget):
    """定时任务项组件"""
    def __init__(self, schedule_data, parent=None):
        super().__init__(parent)
        self.schedule_data = schedule_data
        self.init_ui()
        
    def init_ui(self):
        # 明确使用 QVBoxLayout 和 QHBoxLayout
        main_layout = QVBoxLayout(self)  # 修复此处
        main_layout.setContentsMargins(10, 10, 10, 10)
        main_layout.setSpacing(5)
        
        top_layout = QHBoxLayout()  # 修复此处
        top_layout.setSpacing(10)
        
        # 任务名称和时间信息
        info_layout = QVBoxLayout()
        name_label = QLabel(f"<b>{self.schedule_data['name']}</b>")
        date_time_label = QLabel(f"{self.schedule_data['date']} {self.schedule_data['time']}")
        limit_label = QLabel(f"每日上限: {self.schedule_data['limit']}人")
        info_layout.addWidget(name_label)
        info_layout.addWidget(date_time_label)
        info_layout.addWidget(limit_label)
        
        # 状态标签和操作按钮
        status_label = QLabel("已启用" if self.schedule_data['enabled'] else "已禁用")
        status_label.setStyleSheet(f"background-color: {'#d4edda' if self.schedule_data['enabled'] else '#f8d7da'}; border-radius: 5px;")
        
        toggle_btn = QPushButton()
        toggle_btn.setIcon(QIcon.fromTheme("media-playback-start" if not self.schedule_data['enabled'] else "media-playback-pause"))
        toggle_btn.clicked.connect(self.toggle_status)
        
        delete_btn = QPushButton(QIcon.fromTheme("edit-delete"), "")
        delete_btn.clicked.connect(self.delete_task)
        
        btn_layout = QVBoxLayout()
        btn_layout.addWidget(toggle_btn)
        btn_layout.addWidget(delete_btn)
        
        top_layout.addLayout(info_layout, 1)
        top_layout.addWidget(status_label)
        top_layout.addLayout(btn_layout)
        
        # 重复模式标签
        repeat_label = QLabel(f"重复模式: {self.get_repeat_text()}")
        main_layout.addLayout(top_layout)
        main_layout.addWidget(repeat_label)
        main_layout.addWidget(QFrame(frameShape=QFrame.HLine))
        
        self.setStyleSheet("QWidget { background-color: #fff; border-radius: 5px; }")
    
    def get_repeat_text(self):
        repeat_modes = {'daily': '每天', 'weekdays': '工作日', 'weekends': '周末', 'once': '仅一次'}
        return repeat_modes.get(self.schedule_data['repeat'], self.schedule_data['repeat'])
    
    def toggle_status(self):
        self.schedule_data['enabled'] = not self.schedule_data['enabled']
        self.parent().update_schedule_list()  # 直接调用父窗口方法
    
    def delete_task(self):
        if QMessageBox.question(self, "确认删除", f"删除任务 '{self.schedule_data['name']}'？") == QMessageBox.Yes:
            self.parent().delete_schedule(self.schedule_data['id'])

class ScheduleManagerDialog(QDialog, Ui_ScheduleManagerDialog):
    """定时任务管理对话框"""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setupUi(self)  # 初始化UI
        self.schedules = []
        self.init_data()
        
        # 连接按钮信号
        self.add_btn.clicked.connect(self.add_schedule)
    
    def init_data(self):
        """初始化表单默认值"""
        self.date_input.setDate(QDate.currentDate().addDays(1))
        self.time_input.setTime(QTime.currentTime().addSecs(3600))
        self.limit_input.setValue(20)
        self.update_empty_hint()
    
    def add_schedule(self):
        """添加新任务"""
        name = self.name_input.text().strip() or f"定时任务 {len(self.schedules)+1}"
        date = self.date_input.date().toString("yyyy-MM-dd")
        time = self.time_input.time().toString("HH:mm")
        limit = self.limit_input.value()
        repeat = {
            "每天": "daily",
            "工作日(周一至周五)": "weekdays",
            "周末(周六至周日)": "weekends",
            "仅一次": "once"
        }[self.repeat_select.currentText()]
        
        if any(s['date'] == date and s['time'] == time for s in self.schedules):
            QMessageBox.warning(self, "时间冲突", "该时间点已有任务！")
            return
        
        self.schedules.append({
            'id': len(self.schedules)+1,
            'name': name,
            'date': date,
            'time': time,
            'limit': limit,
            'repeat': repeat,
            'enabled': True
        })
        self.update_schedule_list()
        self.reset_form()
    
    def reset_form(self):
        """重置表单内容"""
        self.name_input.clear()
        self.date_input.setDate(QDate.currentDate().addDays(1))
        self.time_input.setTime(QTime.currentTime().addSecs(3600))
        self.limit_input.setValue(20)
        self.repeat_select.setCurrentIndex(0)
    
    def update_schedule_list(self):
        """更新任务列表显示"""
        self.schedule_list.clear()
        for schedule in self.schedules:
            item = QListWidgetItem()
            item.setSizeHint(QSize(0, 100))
            item_widget = ScheduleItem(schedule, parent=self.schedule_list)
            self.schedule_list.addItem(item)
            self.schedule_list.setItemWidget(item, item_widget)
        self.update_empty_hint()
    
    def update_empty_hint(self):
        """显示/隐藏空状态提示"""
        self.empty_hint.setVisible(len(self.schedules) == 0)
    
    def delete_schedule(self, schedule_id):
        """删除任务"""
        self.schedules = [s for s in self.schedules if s['id'] != schedule_id]
        self.update_schedule_list()

class MainWindow(QDialog):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("演示窗口")
        self.setGeometry(100, 100, 400, 300)
        
        btn = QPushButton("打开任务管理", self)
        btn.clicked.connect(lambda: ScheduleManagerDialog(self).exec_())
        btn.resize(150, 40)
        btn.move(125, 100)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())